import requests
from bs4 import BeautifulSoup
import csv

url = 'http://data.sports.sohu.com/nba/nba_players_rank.php?order_by=points&spm=smpc.fb-nba-home.top-dc.2.1620824904040nf6byr7'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
}

response = requests.get(url, headers=headers)
response.encoding = 'GBK'

soup = BeautifulSoup(response.text, 'html.parser')

with open('NBA_players.csv', 'w', newline='', encoding='utf-8-sig') as f:
    writer = csv.writer(f)

    # 写入表头
    row = ['排名', '球员', '球队', '出场次数', '场均时间', '得分', '命中/出手', '命中率', '命中/三分', '三分命中率', '命中/罚球', '罚球命中率']
    writer.writerow(row)

    # 获取前50名球员信息
    players = soup.find_all('tr')[0:51]
    for player in players:
        # 解析球员信息
        rank = player.contents[1].get_text().strip()
        name = player.contents[3].get_text().strip()
        team = player.contents[5].get_text().strip()
        games = player.contents[7].get_text().strip()
        time = player.contents[9].get_text().strip()
        score = player.contents[11].get_text().strip()
        shots = player.contents[13].get_text().strip()
        shot_pct = player.contents[15].get_text().strip()
        three_shots = player.contents[17].get_text().strip()
        three_pct = player.contents[19].get_text().strip()
        free_shots = player.contents[21].get_text().strip()
        free_pct = player.contents[23].get_text().strip()

        # 写入数据
        row = [rank, name, team, games, time, score, shots, shot_pct, three_shots, three_pct, free_shots, free_pct]
        writer.writerow(row)
